package org.hdl.anima.filter;

import static com.google.common.base.Preconditions.checkArgument;

import java.util.List;

import org.hdl.anima.handler.ServiceHandlers;
import org.hdl.anima.message.IRequest;
import org.hdl.anima.message.ResponseCallback;
import org.hdl.anima.session.ISession;
/**
 * 
 * @author qiuhd
 * @since  2014-7-31
 * @version V1.0.0
 */
public class DefaultFilterChain implements FilterChain{

	private final List<HandlerFilter> filters;
	private final ServiceHandlers handlers;
	private int index = 0;
	
	public DefaultFilterChain(ServiceHandlers handlers,List<HandlerFilter> filters) {
		checkArgument(filters != null,"filters can not be null");
		checkArgument(handlers != null,"handlers can not be null");
		this.filters = filters;
		this.handlers = handlers;
	}
	
	@Override
	public void doFilter(ISession session,IRequest request,ResponseCallback callBack) throws Exception {
		if (index >= filters.size()) {
			handlers.doHandle(request, session,callBack);
			return ;
		}
		HandlerFilter filter = filters.get(index++);
		try {
			filter.doFilter(session,request,callBack,this);
		}catch (Exception e) {
			throw new IllegalStateException("Failed to do filter,filter name :" + filter.getClass().getSimpleName());
		}
	}
}

